package com.my.study.redisson.timer;

import com.my.study.redisson.constant.TaskConstants;
import com.my.study.util.SpringPlusUtils;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 客户端续命
 * 
 * @author: yidujun
 * @create: 2021/11/08 21:19
 */
@Slf4j
@Component
public class RedisClientTimer {

    private AtomicBoolean doIt = new AtomicBoolean(false);

    private final ScheduledExecutorService expireExecutor = new ScheduledThreadPoolExecutor(1,
                                                                        r -> new Thread(r, "ClientExpireTimer"));

    @Resource
    private RedissonClient redissonClient;

    public void doCheck() {
        if (!doIt.getAndSet(true)) {
            expireExecutor.scheduleWithFixedDelay(() -> {
                log.info("===============客户端心跳=============");
                String key = SpringPlusUtils.getClientInfo().toString();
                try {
                    RMap<String, Date> serverList = redissonClient.getMap(TaskConstants.SERVER_LIST);
                    Calendar calendar = Calendar.getInstance();
                    calendar.add(Calendar.SECOND, 40);
                    serverList.put(key, calendar.getTime());
                } catch (Exception e) {
                    log.error("[RedisClientTimer] key:{} 心跳错误", key, e);
                }
            }, 10000, 10000, TimeUnit.MILLISECONDS);
        }
    }



}
